package com.xgc.book.bookserver.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xgc.book.bookserver.bean.*;
import com.xgc.book.bookserver.mapper.BookMapper;
import com.xgc.book.bookserver.mapper.VipMapper;
import com.xgc.book.bookserver.service.*;
import com.xgc.book.bookserver.util.ResultJson;
import com.xgc.book.bookserver.util.form.CommentForm;
import com.xgc.book.bookserver.util.form.LoginForm;
import com.xgc.book.bookserver.util.http.HttpUtils;
import com.xgc.book.bookserver.util.shiro.TokenGenerator;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 会员信息表 服务实现类
 * </p>
 *
 * @author wrz
 * @since 2023-11-20
 */
@Service
@Transactional
public class VipServiceImpl extends ServiceImpl<VipMapper, VipBean> implements VipService {

    @Autowired
    private VipTokenService vipTokenService;
    @Autowired
    private CodeService codeService;
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private BookCommentService bookCommentService;
    @Autowired
    private BookLikeService bookLikeService;
    @Autowired
    private FeedbackService feedbackService;
    @Autowired
    private RecordService recordService;

    @Value("${tx.wx.url}")
    private String wxURL;
    @Value("${tx.wx.appId}")
    private String appId;
    @Value("${tx.wx.secret}")
    private String secret;


    @Override
    public ResultJson login(LoginForm loginForm) {
        if (loginForm.getPhone() == null) {
            return ResultJson.error("手机号不能为空！");
        }
        if (loginForm.getUuid() == null) {
            return ResultJson.error("uuid不能为空");
        }
//        if (!codeService.checkKaptcha(loginForm.getUuid(), loginForm.getCode())) {
//            return ResultJson.error("短信验证码错误！");
//        }

        VipBean vipBean = this.getOne(new QueryWrapper<VipBean>().eq("phone", loginForm.getPhone()));
        if (vipBean == null) {//首次登录则存入数据库
            vipBean = new VipBean();
            vipBean.setPhone(loginForm.getPhone());
            vipBean.setName("读者");
            vipBean.setStatus(1);
            this.save(vipBean);
        }
        //根据会员编号查找token
        VipTokenBean vipToken = vipTokenService.getOne(new QueryWrapper<VipTokenBean>().eq("vip_id",
                vipBean.getVipId()));
        if (vipToken == null) {
            vipToken = new VipTokenBean();
        }
        vipToken.setVipId(vipBean.getVipId());
        vipToken.setToken(TokenGenerator.generateValue());
        vipToken.setType(loginForm.getType());
        Date date = new Date();
        date.setHours(date.getHours() + 6);
        vipToken.setExpires(date);
        vipTokenService.saveOrUpdate(vipToken);
        return ResultJson.ok(vipToken.getToken());
    }

    @Override
    public ResultJson logout(int vipId) {
        VipTokenBean vipTokenBean = vipTokenService.getOne(new QueryWrapper<VipTokenBean>().eq("vip_id", vipId));
        if (vipTokenBean != null) {
            vipTokenBean.setToken(TokenGenerator.generateValue());
            vipTokenService.updateById(vipTokenBean);
        }
        return ResultJson.ok();
    }

    @Override
    public void saveComment(CommentForm comment) {
        BookBean bookBean = new BookBean();
        bookBean.setBookId(comment.getBookId());
        bookBean.setScore(comment.getScore());
        bookMapper.updateScore(bookBean);

        BookCommentBean bookComment = new BookCommentBean();
        bookComment.setCommentTime(new Date());
        bookComment.setContent(comment.getContent());
        bookComment.setVipId(comment.getVipId());
        bookComment.setBookId(comment.getBookId());
        bookCommentService.save(bookComment);
    }

    @Override
    public ResultJson getPage(int page, int limit, VipBean vipBean) {
        IPage<VipBean> iPage = this.page(new Page<>(page, limit), new QueryWrapper<VipBean>()
                .like(StringUtils.isNotEmpty(vipBean.getName()), "name", vipBean.getName())
                .eq(vipBean.getSex() != null, "sex", vipBean.getSex())
                .eq(StringUtils.isNotEmpty(vipBean.getPhone()), "phone", vipBean.getPhone())
                .eq(vipBean.getStatus() != null, "status", vipBean.getStatus())
                .orderByDesc("vip_id"));
        return ResultJson.ok(iPage);
    }

    @Override
    public void deleteVip(int vipId) {
        this.removeById(vipId);
        bookCommentService.remove(new QueryWrapper<BookCommentBean>().eq("vip_id", vipId));
        bookLikeService.remove(new QueryWrapper<BookLikeBean>().eq("vip_id", vipId));
        recordService.remove(new QueryWrapper<RecordBean>().eq("vip_di", vipId));
        feedbackService.remove(new QueryWrapper<FeedbackBean>().eq("user_id", vipId));
    }

    @Override
    public ResultJson wxLogin(String jsCode) {
        /*获取openid*/
        /*封装请求参数*/
        Map<String, String> map = new HashMap<>();
        map.put("appid", appId);
        map.put("secret", secret);
        map.put("grant_type", "authorization_code");
        map.put("js_code", jsCode);
        /*发送请求并获取参数*/
        String result = HttpUtils.sendGet(wxURL, HttpUtils.map2String(map));
        /*解析json对象*/
        JSONObject json = JSON.parseObject(result);
        String openId = json.getString("openid");
        if (StringUtils.isEmpty(openId)) {
            return ResultJson.error(json.getString("errmsg"));
        }
        VipBean vipBean = this.getOne(new QueryWrapper<VipBean>()
                .eq("open_id", openId));
        if (vipBean == null) {
            vipBean = new VipBean();
            vipBean.setOpenId(openId);
            vipBean.setName("微信用户");
            this.save(vipBean);
        }
        VipTokenBean vipTokenBean = vipTokenService.getOne(new QueryWrapper<VipTokenBean>()
                .eq("vip_id", vipBean.getVipId()));
        if (vipTokenBean == null) {
            vipTokenBean = new VipTokenBean();
        }
        vipTokenBean.setVipId(vipBean.getVipId());
        vipTokenBean.setType(2);
        vipTokenBean.setToken(TokenGenerator.generateValue());
        Date date = new Date();
        date.setHours(date.getHours() + 8);
        vipTokenBean.setExpires(date);
        vipTokenService.saveOrUpdate(vipTokenBean);
        return ResultJson.ok(vipTokenBean.getToken());
    }
}
